package top.glkj.hms.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import top.glkj.hms.utils.Status;

import javax.persistence.*;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 用户角色表
 *
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/1 0:35
 */
@Getter
@Setter
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "hms_role")
public class Role extends BaseEntity {
    /**
     * 角色名称
     */
    @Column(nullable = false, name = "role_name")
    private String roleName;
    /**
     * 角色简码
     */
    @Column(unique = true, nullable = false, name = "role_code")
    private String roleCode;
    /**
     * 角色权限
     */
    @Fetch(FetchMode.JOIN)
    @ManyToMany(targetEntity = Permission.class, cascade = CascadeType.ALL)
    @JoinTable(name = "hms_roles_permissions",
            //当前对象在中间表中的外键
            joinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")},
            //对方对象在中间表中的外键
            inverseJoinColumns = {@JoinColumn(name = "permission_id", referencedColumnName = "id")}
    )
    private Set<Permission> permissions= new HashSet<>();
    /**
     * 父级角色
     */
    @OneToOne
    @JoinColumn(name = "role_parent_id", referencedColumnName = "id")
    private Role parent;
    /**
     * 角色描述
     */
    private String description;

    @Transient
    private List<Role> children;

    //@ManyToMany(mappedBy = "roles", fetch = FetchType.EAGER)
    //private Set<User> users = new HashSet<>();
    /**
     * 状态码
     */
    private Status status;

    public Role(Long id) {
        super(id);
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Role)) {
            return false;
        }
        Role role = (Role) o;
        return Objects.equals(getRoleName(), role.getRoleName())
                && Objects.equals(getRoleCode(), role.getRoleCode())
                && Objects.equals(getCreateUserId(), role.getCreateUserId())
                && Objects.equals(getParent(), role.getParent())
                && Objects.equals(getDescription(), role.getDescription())
                && getStatus() == role.getStatus();
    }

    @Override
    public int hashCode() {
        return Objects.hash(getRoleName(),
                getRoleCode(),
                getCreateUserId(),
                getParent(),
                getDescription(),
                getStatus());
    }
}
